package com.dataStructure.复杂度;

public class 菲波拉契数 {
    /**
     * 菲波拉契数
     * 0 1 2 3 4 5 6 7
     * 0 1 1 2 3 5 8 13....  当前数是前面两位数之后
     */

    //求第n个菲波拉契数
    //方法一
    public static int fib(int n) {
        if (n <= 1) return n;
        return fib(n - 1) + fib(n - 2);
    }

    //方法二
    public static int fib2(int n) {
        if (n <= 1) return n;

        int first = 0;
        int second = 1;
        for (int i = 1; i <= n - 1; i++) {
            int sum = first + second;
            first = second;
            second = sum;
        }
        return second;
    }

    //方法三
    public static int fib3(int n) {
        if (n <= 1) return n;
        int first = 0;
        int second = 1;
        while (n-- > 1) {
            second = first + second;
            first = second - first;
        }
        return second;
    }

    public static void main(String[] args) {
        int fib = fib2(10000);
        int fib1 = fib3(10000);
        System.out.println(fib1);
        System.out.println(fib);
    }
}